import {UpdateUserAvatar, uploadUserAvatar} from "../Axios/updtaUser.js"
import {showToast} from "../Toast.js"

const cvs = document.getElementById('image-preview')
const clipCvs = document.getElementById('croppedResult')

//按钮
const submitBtn = document.getElementById('submit-btn')
const fileUpload = document.getElementById('file-upload');

const ctx = cvs.getContext('2d')
const clipCtx = clipCvs.getContext('2d')
const img = new Image()

let fileName = "avatar.jpg"

//裁剪的大小
let size = 150

//图片显示的最大宽度
let maxW = 400

//裁剪的位置
const p = {
    left: 0, top: 0, stepX: 0, stepY: 0
}

const onChange = (file) => {
    onInit(URL.createObjectURL(file))
}

//重置页面
const ResetPage = () => {
    const cropArea = document.getElementById('crop-area');
    const cropped_preview = document.getElementById('cropped-preview-container');
    submitBtn.disabled = true;

    cropArea.style.display = 'none';
    cropped_preview.style.display = 'none';
}

// 加载图片，并初始化裁剪功能
const onInit = (src) => {
    clipCvs.width = clipCvs.height = size
    img.src = src
    img.onload = () => {
        let width = img.width
        let height = img.height
        if (width > maxW) {

            height = maxW / width * height
            width = maxW
        }
        cvs.width = width
        cvs.height = height
        render(width / 2 - size / 2, height / 2 - size / 2)
    }
}
// 渲染裁剪前canvas
const render = (left = 0, top = 0) => {
    ctx.clearRect(0, 0, cvs.width, cvs.height)
    ctx.drawImage(img, 0, 0, cvs.width, cvs.height)
    if (left < 0) {
        left = 0
    }
    if (left > cvs.width - size) {
        left = cvs.width - size
    }
    if (top < 0) {
        top = 0
    }
    if (top > cvs.height - size) {
        top = cvs.height - size
    }
    clipPic(ctx.getImageData(left, top, size, size))
    ctx.beginPath()
    ctx.fillStyle = 'rgba(0, 0, 0, 0.5)'
    ctx.fillRect(left, top, size, size)
    p.left = left
    p.top = top
}
// 裁剪图片，并显示在右侧
const clipPic = (data) => {
    clipCtx.clearRect(0, 0, clipCvs.width, clipCvs.height)
    clipCtx.putImageData(data, 0, 0)
}

let isMoving = false
cvs.onmousedown = (e) => {
    p.stepX = e.pageX - p.left
    p.stepY = e.pageY - p.top
    isMoving = true
}
cvs.onmousemove = (e) => {
    if (isMoving) {
        render(e.pageX - p.stepX, e.pageY - p.stepY)
    }
}
document.onmouseup = () => {
    isMoving = false
}

submitBtn.onclick = async ev => {
    // 转换为 Blob
    clipCvs.toBlob(blob => {
        // 创建 FormData
        const formData = new FormData();
        formData.append('file', blob, fileName);

        // 这里添加上传逻辑
        uploadUserAvatar(formData).then(e => {
            let outcome = e.data.data.uploadFileVo.url;
            console.log(e.data.data)
            //更新用户头像
            UpdateUserAvatar({
                avatar: outcome
            }).then(() => {

                showToast("修改成功", "success")
                setTimeout(function () {
                    // 重置上传文件页面
                    ResetPage()
                }, 400);
            }).catch(ex => {
                showToast(ex.response.data.message, "error")
            })
        }).catch(ex => {
            showToast(ex.response.data.message, "error")
        })

    }, 'image/jpeg');
}

fileUpload.onchange = async (e) => {
    const file = e.target.files[0];

    if (!file) return;
    // 检查文件类型
    if (!file.type.match('image.*')) {
        console.log('请选择图片文件');
        return;
    }

    const cropArea = document.getElementById('crop-area');
    const cropped_preview = document.getElementById('cropped-preview-container');
    // 显示预览
    submitBtn.disabled = false;
    cropArea.style.display = 'inline-block';
    cropped_preview.style.display = 'inline-block';
    // 添加名称
    fileName = file.name

    onChange(file)
}


export {onInit}